<?php
namespace app\index\controller;
use app\common\controller\Homebase;
use app\index\model\Order as Orders;
use app\index\validate\Order;
use think\Db;
class Index extends Homebase
{
    public function index()
    {
        $status = $this->request->param('status');
        $date = $this->request->param('date');
        $area = $this->request->param('area');
        $server = $this->request->param('server');
        $type = $this->request->param('type');
        $search_type = $this->request->param('search_type');
        $keyword = $this->request->param('keyword');
        $order_count = db('order')->alias('a');
        $order = db('order')->alias('a');
        $query = [];
        //时间
        if($date){
            $query['date'] = $date;
            $date = explode('-',$date);
            $order_count->where('a.create_time','between',[strtotime($date[0]),strtotime($date[1])]);
            $order->where('a.create_time','between',[strtotime($date[0]),strtotime($date[1])]);            
        }
        //区
        if($area){
            $order_count->where('a.area','like','%'.$area.'%');
            $order->where('a.area','like','%'.$area.'%');
            $query['area'] = $area;
        }
        //服
        if($server){
            $order_count->where('a.server','like','%'.$server.'%');
            $order->where('a.server','like','%'.$server.'%');
            $query['server'] = $server;
        }
        if($type){
            $order_count->where('a.type','like','%'.$type.'%');
            $order->where('a.type','like','%'.$type.'%');
            $query['type'] = $type;
        }
        //关键字
        if($search_type == 5 && $keyword){
            $order->join('tf_user u','a.mid = u.id','LEFT')->join('tf_user s','a.customer_id = s.id');
        }else if($search_type == 8 && $keyword){
            $order->join('tf_user u','a.mid = u.id')->join('tf_user s','a.customer_id = s.id','LEFT');
        }else{
            $order->join('tf_user u','a.mid = u.id','LEFT')->join('tf_user s','a.customer_id = s.id','LEFT');
        }
        if($keyword){
            if($search_type == 1){
                $order_count->where('a.role','like','%'.$keyword.'%');
                $order->where('a.role','like','%'.$keyword.'%');
            }else if($search_type == 2){
                $order_count->where('a.iphone','like','%'.$keyword.'%');
                $order->where('a.iphone','like','%'.$keyword.'%');
            }else if($search_type == 3){
                $order_count->where('a.taobao','like','%'.$keyword.'%');
                $order->where('a.taobao','like','%'.$keyword.'%');                
            }else if($search_type == 4){
                $order_count->where('a.login','like','%'.$keyword.'%');
                $order->where('a.login','like','%'.$keyword.'%');                
            }else if($search_type == 5){
                $order_count->join('tf_user u','a.customer_id = u.id')->where('u.name','like','%'.$keyword.'%');
                $order->where('s.name','like','%'.$keyword.'%');                
            }else if($search_type == 6){
                $order_count->where('a.number','like','%'.$keyword.'%');
                $order->where('a.number','like','%'.$keyword.'%');                  
            }else if($search_type == 7){
                $order_count->where('a.content','like','%'.$keyword.'%');
                $order->where('a.content','like','%'.$keyword.'%');                   
            }else if($search_type == 8){
                $order_count->join('tf_user u','a.mid = u.id')->where('u.name','like','%'.$keyword.'%');
                $order->where('u.name','like','%'.$keyword.'%');                  
            }
        }
        if(!isset($this->request->param()['status'])){
            $order_count->where('a.status','>',-1);
            $order->where('a.status','>',-1);            
        }else if($status == 'all'){
            $order_count->where('a.status','>',-1);
            $order->where('a.status','>',-1);
        }else if(intval($status) === 0){
            $order_count->where('a.status',0);
            $order->where('a.status',0);
        }else if($status){
            $order_count->where('a.status',$status);
            $order->where('a.status',$status);
        }else{
            $order_count->where('a.status','>',-1);
            $order->where('a.status','>',-1);
        }
        $count = $order_count->count();
        $data = $order->field('a.*,u.name as membername,s.name as servername')->order('id desc')->paginate(10,$count,['query'=>$query]);
        $this->assign('count',$count);
        $this->assign('data',$data);
        $this->assign('tags',db('tags')->select());
        //获取订单数量
        $tongji = Db::query("select  sum(if(status=0,1,0)) as sum0 ,sum(if(status=1,1,0)) as sum1,sum(if(status=2,1,0)) as sum2,sum(if(status=3,1,0)) as sum3,sum(if(status=4,1,0)) as sum4,sum(if(status=5,1,0)) as sum5,sum(if(status=6,1,0)) as sum6,sum(if(status=7,1,0)) as sum7,sum(if(status=8,1,0)) as sum8,sum(if(status=9,1,0)) as sum9,sum(if(status=10,1,0)) as sum10,sum(if(status=11,1,0)) as sum11 from tf_order");
        $this->assign('tongji',$tongji[0]);
        return $this->fetch();
    }

    //获取修改备注
    public function getRemark(){
        if($this->request->isPost()){
            $data = $this->request->param();
            $data['update_time'] = time();
            $res = db('order')->update($data);
            if($res!==false){
                db('order_log')->insert(['order_id'=>$data['id'],'name'=>session('userinfo')['name'],'msg'=>'订单备注修改为 <span style="color:red;">'.$data['remark'].'</span>','create_time'=>time()]);
                return ['code'=>1,'msg'=>'修改成功'];
            }
            return ['code'=>0,'msg'=>'修改失败'];
        }
        $id = $this->request->param('id');
        $remark = db('order')->where('id',$id)->value('remark');
        return ['code'=>1,'msg'=>$remark];
    }
    //标签
    public function addTags(){
        $id = $this->request->param('id');
        $tags_id = $this->request->param('tags_id');
        $res = db('order')->where('id',$id)->update(['tags_id'=>$tags_id,'update_time'=>time()]);
        if($res!==false){
            if($tags_id){
                $tagname = db('tags')->where('id',$tags_id)->value('title');
                db('order_log')->insert(['order_id'=>$id,'name'=>session('userinfo')['name'],'msg'=>'订单标签修改为 <span style="color:red;">'.$tagname.'</span>','create_time'=>time()]);
            }else{
                db('order_log')->insert(['order_id'=>$id,'name'=>session('userinfo')['name'],'msg'=>'订单标签修改为 <span style="color:red;">无</span>','create_time'=>time()]);     
            }
            return ['code'=>1,'msg'=>'修改成功'];
        }
        return ['code'=>0,'msg'=>'修改失败'];
    }
    //加急
    public function urgent(){
        $id = $this->request->param('id');
        $is_urgent = $this->request->param('is_urgent');
        if($is_urgent){
            $res = db('order')->where('id',$id)->update(['is_urgent'=>0,'update_time'=>time()]);
        }else{
            $res = db('order')->where('id',$id)->update(['is_urgent'=>1,'update_time'=>time()]);
        }
        if($res!==false){
            if($is_urgent){
                db('order_log')->insert(['order_id'=>$id,'name'=>session('userinfo')['name'],'msg'=>'加急与否从不加急修改为 <span style="color:red;">取消加急</span>','create_time'=>time()]);
            }else{
                db('order_log')->insert(['order_id'=>$id,'name'=>session('userinfo')['name'],'msg'=>'加急与否从不加急修改为 <span style="color:red;">加急</span>','create_time'=>time()]);
            }            
            return ['code'=>1,'msg'=>'操作成功'];
        }
        return ['code'=>0,'msg'=>'操作失败'];
    }
    //修改状态
    public function changeOrderStatus(){
        $id = $this->request->param('id');
        $status = $this->request->param('status');
        $res = db('order')->where('id',$id)->update(['status'=>$status,'update_time'=>time()]);
        if($res!==false){
            $arr[1] = '代练中';$arr['2']='待验收';$arr['3']='已完成';$arr['4']='已结算';$arr['5']='已仲裁';$arr['6']='已撤销';$arr['8']='已锁定';$arr['9']='异常中';$arr['10']='仲裁中';
            db('order_log')->insert(['order_id'=>$id,'name'=>session('userinfo')['name'],'msg'=>'订单状态修改为 <span style="color:red;">'.$arr[$status].'</span>','create_time'=>time()]);

            //写查询日志
            if ($status==3) {
               $data['order_id'] = $id;
               $data['msg'] = '订单已完成，有任何问题可以与客服联系。';
               $data['name'] = session('userinfo.name');
               $data['create_time'] = time();
               Db('order_search')->insert($data); 
            }
            return ['code'=>1,'msg'=>'操作成功'];
        }
        return ['code'=>0,'msg'=>'操作失败'];
    }
    public function add(){
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $ordre_model = new Orders();
            $import = db("import")->select();
            $ext = [];
            foreach ($import as $key => $va) {
               $array[$va['value']] = $va;  
            }
            unset($import);
            $new = ['auther1','auther2','auther3','auther4','auther5','auther6'];
            foreach ($data as $k => $v) {
                if(in_array($k, $new)){
                    $ext[$k]['name'] = $array[$k]['name'];
                    $ext[$k]['is_text'] = $array[$k]['is_text'];
                    $ext[$k]['value'] = $v;
                }else{
                    if(isset($array[$k])){
                        $ext[$k] = $array[$k]['name'];
                    }
                }
            }
            unset($new);
            unset($array);
            $data['ext'] = serialize($ext);
            $data['time'] = $data['time']?$data['time']*86400:'0';
            $data['ordertime'] = !empty($data['ordertime'])?$data['ordertime']*86400:'0';
            $result = $ordre_model->validate('Order.add')->allowField(true)->save($data);
            if ($result) {
                $arr['order_id'] = $ordre_model->id;
                $arr['msg'] = '订单已创建，正在处理中,有任何问题可以与客服联系。';
                $arr['name'] = session('userinfo.name');
                $arr['create_time'] = time();
                Db('order_search')->insert($arr);
            	return ['code'=>1,'msg'=>'添加成功'];
            }else{
                return ['code'=>0,'msg'=>$ordre_model->getError()];
            }
        }else{
            $imports = Db('import')->where('status',1)->select();
            $customer = Db('user')->where(['group_id'=>3,'status'=>1])->select();
            $tags = Db('tags')->where('status',1)->select();
            $this->assign('imports',$imports);
            $this->assign('customer',$customer);
            $this->assign('tags',$tags);
            return $this->fetch();
        }
    }
    //删除
    public function del(){
        $id = $this->request->param('id');
        $res = db('order')->where('id',$id)->update(['status'=>'-1','update_time'=>time()]);
        if($res!==false){
            db('order_log')->insert(['order_id'=>$id,'name'=>session('userinfo')['name'],'msg'=>'订单状态修改为 <span style="color:red;">删除</span>','create_time'=>time()]);
            return ['code'=>1,'msg'=>'删除成功'];
        }
        return ['code'=>0,'msg'=>'删除失败'];
    }

    //检测订单号唯一
    public function checkNumber(){
        $number = $this->request->post('number');
        if (!Db('order')->where('number',$number)->find()) {
            return ['code'=>1,'msg'=>'订单编号可用'];
        }else{
            return ['code'=>0,'msg'=>'此订单编号已存在'];
        }
    }
    //退款
    public function callback(){
        $id = $this->request->param('id');
        $data = db('order')->where('id',$id)->find();
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if(!$data['back_paymoney']){
                return ['code'=>0,'msg'=>'退款金额不能为0'];
            }
            if(!$data['back_reason']){
                return ['code'=>0,'msg'=>'退款原因必须填写'];
            }
            $data['update_time'] = time();
            $data['status'] = 7;
            $res = db('order')->update($data);
            if($res!==false){
                db('order_log')->insert(['order_id'=>$id,'name'=>session('userinfo')['name'],'msg'=>'订单状态修改为 <span style="color:red;">退款</span>','create_time'=>time()]);
                return ['code'=>1,'msg'=>'退款成功'];
            }
            return ['code'=>0,'msg'=>'退款失败'];
       }
        $this->assign('data',$data);
        return $this->fetch();
    }

    //修改
    public function edit(){
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $order = db('order')->where('id',$data['id'])->find();
            $new = ['auther1','auther2','auther3','auther4','auther5','auther6'];
            $ext = unserialize($order['ext']);
            foreach ($data as $key => $va) {
                if(in_array($key,$new) && isset($ext[$key])){
                    $ext[$key]['value'] = $va;
                }
            }
            $data['ext'] = serialize($ext);
            $data['update_time'] = time();
            if(isset($data['time'])){
                $data['time'] = 86400*$data['time'];
            }
            if(isset($data['ordertime'])){
                $data['ordertime'] = 86400*$data['ordertime'];
            }
            $res = db("order")->update($data);
            if ($res) {
                return ['code'=>1,'msg'=>'修改成功'];
            }else{
                return ['code'=>0,'msg'=>'修改失败'];
            }
        }
        $id = $this->request->param('id');
        $data = db('order')->where('id',$id)->find();
        $order_log = db('order_log')->where('order_id',$id)->order('id desc')->select();
        $this->assign('data',$data);
        $this->assign('order_log',$order_log);
        return $this->fetch();
    }

    //发单
    public function sendOrder(){
        $user_count = db('user');
        $user = db('user');
        $name = $this->request->param('name');
        $username = $this->request->param('username');
        $query = [];
        if($name){
            $user_count->where('name','like','%'.$name.'%');
            $user->where('name','like','%'.$name.'%');
            $query['name'] = $name;
        }
        if($username){
            $user_count->where('username','like','%'.$username.'%');
            $user->where('username','like','%'.$username.'%');
            $query['username'] = $username;
        }
        //获取打手
        $count = $user_count->where('group_id',2)->where('status',1)->count();
        $member = $user->where('group_id',2)->where('status',1)->paginate(10,$count,['query'=>$query]);
        $this->assign('member',$member);
        $id = $this->request->param('id');
        $this->assign('id',$id);
        return $this->fetch();
    }
    //选定打手
    public function choseMember(){
        $id = $this->request->param('id');
        $mid = $this->request->param('mid');
        $res =db('order')->where('id',$id)->update(['mid'=>$mid,'update_time'=>time(),'status'=>11]);
        if($res!==false){
            db('order_log')->insert(['order_id'=>$id,'name'=>session('userinfo')['name'],'msg'=>'订单状态修改为 <span style="color:red;">未接手</span>','create_time'=>time()]);
            return ['code'=>1,'msg'=>'分配成功'];
        }
        return ['code'=>0,'msg'=>'分配失败'];
    }
    //完成订单
    public function complete(){
    	$search = $this->request->get();
    	if (!empty($search['date'])) {
    		 $time = explode(" - ", $search['date']);
    	     $where['create_time'] = ['between',[$time[0],$time[1]]];
    	}
    	if (!empty($search['mid'])) {
    		$where['mid'] = $search['mid'];
    	}
    	if (!empty($search['number'])) {
    		$where['number'] = $search['number'];
    	}
    	$where['status'] = 3;
    	$where['is_settlement'] = 0;
    	$ordre_model = new Orders();
        $data = $ordre_model->where($where)->paginate(20);        
        $mids = Db('user')->where('group_id',2)->select();
        $this->assign('mids',$mids);
        $this->assign('data',$data);
        return $this->fetch();
    }

    //生成结算单
    public function createBill(){
    	$search = $this->request->get();
    	if (!empty($search['date'])) {
    		 $time = explode(" - ", $search['date']);
    	     $where['create_time'] = ['between',[$time[0],$time[1]]];
    	}
    	if (!empty($search['mid'])) {
    		$where['mid'] = $search['mid'];
    	}
    	if (!empty($search['number'])) {
    		$where['number'] = $search['number'];
    	}
    	$where['status'] = 3;
    	$where['is_settlement'] = 0;
    	$ordre_model = new Orders();
        $datalist = $ordre_model->where($where)->select();
        $data['number'] = 0;
        $data['money'] = 0.00;
        $ids = [];
        foreach ($datalist as $key => $val) {
        	$data['number']++;
        	$data['money']+=$val['ordermoney'];
        	$ids[] = $val['id']; 
        }
        $data['bill'] = date("YmdHis").time();
        $data['create_time'] = time();
        $data['uid'] = session('userinfo.id');
        $rs = Db('bill')->insert($data);
        if ($rs) {
        	$ordre_model->where('id','in',$ids)->update(['is_settlement'=>1]);
        	return ['code'=>1,'msg'=>'内群账单生成成功'];
        }else{
        	return ['code'=>0,'msg'=>'内群账单生成失败'];
        }
    }
    //内群账单
    public function bill(){
    	$bill_model =  Db('bill');
        $datalist = $bill_model->order('status asc')->paginate(20);
        $this->assign('datalist',$datalist);
        return $this->fetch();
    }

    public function delbill(){
        $id = $this->request->post('id');
        $rs =Db('bill')->where('id',$id)->delete();
        if ($rs!==false) {
        	return ['code'=>1,'msg'=>'删除成功'];
        }else{
        	return ['code'=>0,'msg'=>'删除失败'];
        }
    }

    public function changeStatus(){
    	$id = $this->request->post('id');
        $rs =Db('bill')->where('id',$id)->update(['status'=>1]);
        if ($rs!==false) {
        	return ['code'=>1,'msg'=>'处理成功'];
        }else{
        	return ['code'=>0,'msg'=>'处理失败'];
        }
    }

    //批量导出elx
    public function download(){
         ob_end_clean();
         ob_start();
         vendor('PHPExcel/Classes/PHPExcel');
        $cfg_columns = array(
            'number'=>array('name'=>'订单号'),
            'create_time'=>array('name'=>'录单时间'),
            'area'=>array('name'=>'游戏区'),
            'server'=>array('name'=>'游戏服'),
            'content'=>array('name'=>'代练内容'),
            'price'=>array('name'=>'接单价'),
            'orderpeice'=>array('name'=>'发单价'),
            'role'=>array('name'=>'角色名'),
            'taobao'=>array('name'=>'客户旺旺'),
            'servername'=>array('name'=>'客服'),
            'remark'=>array('name'=>'备注'),
        );
        $ids = $this->request->param('ids');
        $ids = explode(',',$ids); 
        $list = db('order')->alias('a')->where('a.id','in',$ids)->join('tf_user u','a.mid = u.id','LEFT')->join('tf_user s','a.customer_id = s.id','LEFT')->field('a.*,u.name as membername,s.name as servername')->select();
        $filename = 'orders.xls';
        header('Pragma:public');
        header('Content-Type:application/x-msexecl;name="'.$filename.'"');
        header('Content-Disposition:inline;filename="'.$filename.'"');

        $objPHPExcel = new \PHPExcel();

        $objPHPExcel->getActiveSheet(0)->mergeCells('B1:D1');
        $export_time = date('Y-m-d H:i:s');
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', '导出时间:');
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('B1', $export_time);

        $cols = 'A';
        foreach ($cfg_columns as $val){
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cols++.'2',$val['name']);
        }

        //第三行, 输出详细数据
        $rows = 3;
        foreach ($list as $fields){
            $cols = 'A';
            //按cfg_column的配置项导出
            foreach ($cfg_columns as $k => $val){
                if(empty( $fields[$k])){
                    $objPHPExcel->getActiveSheet()->setCellValue($cols++.$rows, 0);
                }else{
                    if ($k == 'create_time') {
                        $fields[$k] = date('Y-m-d H:i',$fields[$k]);
                    }
                    $objPHPExcel->getActiveSheet()->setCellValue($cols++.$rows, $fields[$k]);
                }

            } 

            $rows ++;
        }
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }

    public function downloadtxt(){
        $ids = $this->request->param('ids');
        $ids = explode(',',$ids); 
        $list = db('order')->alias('a')->where('a.id','in',$ids)->join('tf_user u','a.mid = u.id','LEFT')->join('tf_user s','a.customer_id = s.id','LEFT')->field('a.*,u.name as membername,s.name as servername')->select();
        $this->assign('list',$list);
        return $this->fetch();
    }
}
